import React, { ReactText, useEffect, useRef } from 'react';
import { Form, Input, message, Modal } from 'antd';

import { getSmsTempInfo, getSmsTempList, createRobot, modifyRobot } from 'admin/servers/servers';
import TextArea from 'antd/lib/input/TextArea';
import {
  FetchDataParam,
  FetchDataResponse,
  FetchRecordResponse,
  PageSelect,
} from 'components/UILibrary/pageSelect';
import { verifyNull } from 'utils/tools';
import { RobotInfo } from 'admin/schema/Robots';
// 机器人新增和编辑-入参
type IProps = {
  visible: boolean;
  formData: RobotInfo;
  callBack: Function;
};

const RobotPop: React.FC<IProps> = ({ visible, formData, callBack }) => {
  const [form] = Form.useForm();
  const beforeSmsSelectRef = useRef<any>();
  const answerByeSelectRef = useRef<any>();
  const noAnswerByeSelectRef = useRef<any>();

  useEffect(() => {
    if (formData.robotId) {
      // 编辑弹窗-初始化数据
      form.setFieldsValue(formData);
      const { beforeCallSmsTempId, sysAnswerByeTempId, sysNoanswerByeTempId } = formData;

      // 根据name查找短信模板选项-回显
      if (beforeCallSmsTempId) {
        const templateId = beforeCallSmsTempId;
        beforeSmsSelectRef.current?.setValue(templateId as number);
      }
      if (sysAnswerByeTempId) {
        const templateId = sysAnswerByeTempId;
        answerByeSelectRef.current?.setValue(templateId as number);
      }
      if (sysNoanswerByeTempId) {
        const templateId = sysNoanswerByeTempId;
        noAnswerByeSelectRef.current?.setValue(templateId as number);
      }
    }
  }, [form, formData]);

  /**
   * 查找短信模板的dataProvider
   */
  const fetchSmsTempList = (args: FetchDataParam): FetchDataResponse => {
    return new Promise(resolve => {
      getSmsTempList({
        pageNo: args.pageNum,
        pageSize: args.pageSize,
        templateName: args.keywords,
      })
        .then(res => {
          resolve({
            data: res.data?.map(item => {
              return {
                label: item.templateName,
                value: item.templateId,
              };
            }),
            total: res.count as number,
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  };
  /**
   * pageSelect setValue时查记录的函数:根据id
   */
  const fetchSmsTempRecord = (templateId: ReactText): FetchRecordResponse => {
    return new Promise(resolve => {
      getSmsTempInfo(templateId as number)
        .then(res => {
          const item = res.data;
          resolve({
            label: item.templateName,
            value: item.templateId,
            data: item, // 便于onChange判断，有data则回显赋值不用更新数据
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  };
  const handleOK = () => {
    form.validateFields().then(() => {
      console.log('表单验证通过');
      // 表单验证通过
      const val = form.getFieldsValue() as RobotInfo;
      console.log(val, '+++提交表单');
      // 请求接口
      if (!formData.robotId) {
        createRobot({ ...val })
          .then(res => {
            message.success('创建成功');
            // 关闭弹窗-需要刷新列表
            callBack(true);
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      } else {
        modifyRobot(formData.robotId, { ...val })
          .then(res => {
            message.success('编辑成功');
            // 关闭弹窗
            callBack(true);
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      }
    });
  };
  // 关闭弹窗
  const handleClose = () => {
    console.log('操作-关闭');
    callBack();
  };

  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 18 },
  };

  return (
    <Modal
      width={600}
      title={formData.robotId ? '编辑机器人' : '新建机器人'}
      visible={visible}
      onOk={handleOK}
      onCancel={handleClose}
      destroyOnClose
    >
      <Form {...layout} form={form} layout="horizontal">
        <Form.Item
          label="机器人名称"
          name="robotName"
          rules={verifyNull('请输入机器人名称')}
          getValueFromEvent={event => {
            return event.target.value.replace(/\s+/g, '');
          }}
        >
          <Input placeholder="请输入0-30位以内字符" maxLength={30} allowClear />
        </Form.Item>
        <Form.Item label="描述" name="robotDescribe">
          <TextArea rows={5} placeholder="请输入0-50位以内字符" maxLength={50} />
        </Form.Item>
        {/* <Form.Item label="呼前短信" name="beforeCallSmsTempId">
          <PageSelect
            key="beforeSmsSelectRef"
            ref={beforeSmsSelectRef}
            fetchData={fetchSmsTempList}
            placeholder="请选择短信模板"
            fetchRecord={fetchSmsTempRecord}
            allowClear
          />
        </Form.Item>
        <Form.Item label="呼通挂机短信" name="sysAnswerByeTempId">
          <PageSelect
            key="answerByeSelectRef"
            ref={answerByeSelectRef}
            fetchData={fetchSmsTempList}
            placeholder="请选择短信模板"
            fetchRecord={fetchSmsTempRecord}
            allowClear
          />
        </Form.Item>
        <Form.Item label="未呼通挂机短信" name="sysNoanswerByeTempId">
          <PageSelect
            key="noAnswerByeSelectRef"
            ref={noAnswerByeSelectRef}
            fetchData={fetchSmsTempList}
            placeholder="请选择短信模板"
            fetchRecord={fetchSmsTempRecord}
            allowClear
          />
        </Form.Item> */}
      </Form>
    </Modal>
  );
};

export default RobotPop;
